package cn.javaSong.service.impl;

import cn.javaSong.common.ResponseHelper;
import cn.javaSong.common.ResponseModel;
import cn.javaSong.entity.Img;
import cn.javaSong.mapper.ImgMapper;
import cn.javaSong.service.IImgService;
import cn.javaSong.utils.StringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dakai
 * @since 2024-10-30
 */
@Service
public class ImgServiceImpl extends ServiceImpl<ImgMapper, Img> implements IImgService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ImgMapper imgMapper;

    @Value("${songFilePath}")
    private String songFilePath;

    @Value("${server.port}")
    private String imgUrl;



    @Override
    public ResponseModel<Img> getPcGirlWallpaper() {
        String url = "https://api.vvhan.com/api/wallpaper/pcGirl?type=json";
        ResponseEntity<Img> response = restTemplate.getForEntity(url, Img.class);
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            Img img = new Img();
            img.setId(StringUtil.createUUID());
            img.setSuccess(response.getBody().getSuccess());
            img.setType(response.getBody().getType());
            img.setUrl(response.getBody().getUrl());
            String names = StringUtil.getCurrentDateStr();
            String imageName = names + ".png";
            img.setIname(imageName);
            File imageFile = new File(Paths.get(songFilePath, imageName).toString());
            img.setPath(String.valueOf(imageFile));
            try {
                img.setAddress("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + imgUrl + "/song/img/" + imageName);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            RestTemplate restTemplate = new RestTemplate();
            byte[] imageBytes = restTemplate.getForObject(response.getBody().getUrl(), byte[].class);
            try {
                FileUtils.writeByteArrayToFile(imageFile, imageBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            this.save(img);
            return ResponseHelper.dataMessage(img, "添加成功");
        } else {
            return ResponseHelper.successMessage("获取失败！请重新尝试");
        }
    }

    @Override
    public void delImg(String iname) {
        imgMapper.delImg(iname);
    }
}
